package com.yanqu.road.server.timer;

import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.server.connect.CrossAgentLinkedControl;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.rank.CrossGroupUserMonthAbilityRankMgr;
import com.yanqu.road.server.manager.rank.CrossRankMgr;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.executor.GeneralTask;

import java.util.List;

/**
 */
public class CrossMonthAbilityRankUploadNotifyTask extends GeneralTask {
    private boolean isRun;

    @Override
    public void doRun() {
        try {
            if (!isRun) {
                isRun = true;
                int channelId = ConfigHelper.getInt("channelId");
                RankProto.CrossNotifyUploadRankDataMsg.Builder reqMsg = RankProto.CrossNotifyUploadRankDataMsg.newBuilder();
                YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_CROSS_NOTIFY_UPLOAD_RANK_DATA_TO_UNION_CROSS, reqMsg);
                List<CrossUnionServerGroup> groupList = CrossUnionServerGroupMgr.getServerGroupList(channelId);
                for (CrossUnionServerGroup unionServerGroup : groupList) {
                    if (unionServerGroup.getState() == 0) {
                        continue;
                    }
                    if (unionServerGroup.getServerList().size() < GameConfig.UNION_PLAYER_OPEN_COND_AREA_NUM) {
                        //没达到区服数条件的不拉数据
                        continue;
                    }
                    for (Long serverId : unionServerGroup.getServerList()) {
                        if (!CrossAgentLinkedControl.isSeverIdConnection(serverId)) {
                            continue;
                        }
                        if (!CrossGroupUserMonthAbilityRankMgr.isUploadOver(serverId)) {
                            MessageHelper.sendPacket(serverId, 0, message);
                        }
                    }
                }

                CrossGroupUserMonthAbilityRankMgr.checkGroupUploadOverTask();
            }
        } catch (Exception e) {
            CrossRankMgr.getLogger().error("notify upload rank error", e);
        } finally {
            isRun = false;
        }

    }
}